const app = getApp()
import { formatTimeTwo } from '../../utils/util'
import { getMaterialDetail, getMaterialCommentList, postMaterialComment, markMaterial, getUserCollection, addUserCollection, postAddCart, moveMarkMaterial, getMaterialCaseList, shareQrCode } from '../../api/index'

Page({
  data: {
    id: '',
    caseSwiperIndex: 0,
    showDetailLen: 1,
    detail: {
      fileGridMapping: [],
      params: [],
      spce: [],
      markCollectionList: []
    },
    scrollTop: 0,
    commentList: [],
    showSpec: false,
    showProject: false,
    current: {},
    safeBottom: 0,
    showCommentInput: false,
    inputFocus: false,
    currentItem: {},
    currentComment: null,
    showAllComment: false,
    showFavorite: false,
    favorites: [],
    showFavoriteModal: false,
    pageSize: 15,
    currentPage: 1,
    isEmpty: false,
    howBack: false,
    shareModal: false,
    showParamsPop: false,
    showSamplePop: false,
    caseList: [],
    userInfo: {},
    indicatorDots: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    activeIndex: 0
  },
  switchCard (e) {
    let current = e.detail.current
    this.setData({ activeIndex: current })
  },
  seeDetail ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/caseDetail/index?id=${item.materialCaseId}`)
  },
  async joinOrder ({ detail }) {
    try {
      await postAddCart({ ...detail })
      wx.showToast({ title: '已加入样品集装箱', icon: 'none' })
      this.setData({ showSamplePop: false })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  closeSamplePop () {
    this.setData({ showSamplePop: false })
  },
  selectSample ({ detail }) {
    this.setData({ showSamplePop: true, current: detail })
  },
  pageScroll ({ detail: { scrollTop } }) {
    const { screenHeight } = app.globalData.systemInfo
    if (scrollTop >= screenHeight) {
      this.setData({ showBack: true })
    } else {
      this.setData({ showBack: false })
    }
  },
  async onShareAppMessage () {
    try {
      wx.showLoading({ title: '正在生成分享...', mask: true })
      const { ResultSet } = await shareQrCode({ scene: '1' })
      wx.hideLoading()
      this.setData({ shareModal: false })
      return {
        title: `${ResultSet.userData.title}`,
        path: `/pages/index/index`,
        imageUrl: ResultSet.userData.img
      }
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  selectParams () {
    this.setData({ showParamsPop: true })
  },
  closeParamsPop () {
    this.setData({ showParamsPop: false })
  },
  goTop () {
    this.setData({ scrollTop: 0 })
  },
  sharePoster () {
    this.setData({
      shareModal: true
    })
  },
  closeShareModal () {
    this.setData({ shareModal: false })
  },
  showPosterModal () {
    this.setData({ shareModal: false, showPoster: true })
  },
  closePosterModal () {
    this.setData({ showPoster: false })
  },
  changeCaseSwiper ({ detail: { current } }) {
    this.setData({ caseSwiperIndex: current })
  },
  seeSupplier () {
    wx.$nav.navigateTo(`/pages/supplier/index/index?id=${this.data.detail.Material.companyContactId}&name=${this.data.detail.Material.supplierName}`)
  },
  spreadMore () {
    if (this.data.showDetailLen <= 1) this.data.showDetailLen = 10000
    else this.data.showDetailLen = 1
    this.setData({ showDetailLen: this.data.showDetailLen })
  },
  selectSpec () {
    if (this.data.userInfo.userId) {
      this.setData({ showSpec: true })
    } else {
      wx.$nav.navigateTo(`/pages/login/index`)
    }
  },
  closeSpecModal () {
    this.setData({ showSpec: false })
  },
  joinProject ({ detail }) {
    this.setData({ showProject: true, current: detail })
  },
  closeProjectModal () {
    this.setData({ showProject: false })
  },
  postCmoment () {
    if (!this.data.userInfo.userId) {
      wx.$nav.redirectTo(`/pages/login/index`)
      return
    }
    this.setData({ showCommentInput: true })
  },
  closeCommentModal () {
    this.setData({ showCommentInput: false })
    this.getCommentList()
  },
  replyComment ({ detail }) {
    this.setData({
      showCommentInput: true,
      currentComment: detail
    })
  },
  showAllCommentModal ({ currentTarget: { dataset: { item } } }) {
    this.setData({ showAllComment: true, currentItem: item })
    wx.setPageStyle({
      style: {
        overflow: 'hidden'
      }
    })
  },
  closeAllComment () {
    this.setData({ showAllComment: false, currentItem: null })
    wx.setPageStyle({
      style: {
        overflow: ''
      }
    })
  },
  async collection () {
    try {
      if (!this.data.userInfo.userId) {
        wx.$nav.redirectTo(`/pages/login/index`)
        return
      }
      let query = { materialId: this.data.detail.Material.id }
      await markMaterial({ ...query })
      this.data.detail.isMark = !this.data.detail.isMark
      this.setData({ 'detail.isMark': this.data.detail.isMark })
      if (this.data.detail.isMark) {
        await this.getFavorites()
        this.setData({ showFavorite: true })
      } else {
        wx.showToast({ title: '取消收藏成功！', icon: 'none' })
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async selectFavorite ({ currentTarget: { dataset: { item } } }) {
    try {
      let query = {
        materialId: this.data.detail.Material.id, newCollectionId: item.id, oldCollectionId: this.data.detail.markCollectionList[0]
      }
      await moveMarkMaterial({ materialId: this.data.detail.Material.id, newCollectionId: item.id, oldCollectionId: this.data.detail.markCollectionList[0] })
      wx.showToast({ title: '收藏成功！', icon: 'none' })
      this.setData({ showFavorite: false })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
    // await this.markMaterial(item.id)
    // this.setData({ showFavorite: false })
  },
  async markMaterial (collectionId = '') {
    try {
      let query = { materialId: this.data.detail.Material.id }
      if (collectionId) query.collectionId = collectionId
      await markMaterial({ ...query })
      this.data.detail.isMark = !this.data.detail.isMark
      this.setData({ 'detail.isMark': this.data.detail.isMark })
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  newAdd () {
    this.setData({ showFavoriteModal: true })
  },
  closeFavorite () {
    this.setData({ showFavoriteModal: false })
  },
  closeFavoriteSheet () {
    this.setData({ showFavorite: false })
  },
  async confirmFavorite ({ detail }) {
    try {
      await addUserCollection({ ...detail })
      wx.showToast({ title: '创建成功！', icon: 'none' })
      this.getFavorites()
      this.setData({ showFavoriteModal: false })
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async sendComment ({ detail }) {
    try {
      let query = {
        materialId: this.data.id,
        commentContext: detail
      }
      if (this.data.currentComment) {
        query.parentId = this.data.currentComment.id
        query.topId = this.data.currentComment.id
      }
      await postMaterialComment({...query})
      wx.showToast({ title: '评论成功！', icon: 'none' })
      this.setData({
        showCommentInput: false,
        currentComment: null
      })
      this.getCommentList()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async confirmComment ({ detail: { value } }) {
    try {
      await postMaterialComment({ materialId: this.data.id, commentContext: value })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getFavorites () {
    try {
      const { ResultSet } = await getUserCollection()
      this.setData({
        favorites: ResultSet.userData.userCollections
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getMaterialCaseList () {
    try {
      const { ResultSet } = await getMaterialCaseList({ currentPage: 1, pageLines: 3, materialId: this.data.id })
      // ResultSet.userData.caseList.forEach(item => {
      //   if (item.type)
      // })
      this.setData({ caseList: ResultSet.userData.caseList })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  seeMoreCase () {
    wx.$nav.navigateTo(`/pages/moreCase/index?id=${this.data.detail.Material.id}`)
  },
  async getDetail () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      const { ResultSet } = await getMaterialDetail({ materialId: this.data.id })
      this.setData({
        detail: ResultSet.userData,
      })
      await this.getMaterialCaseList()
      await this.getCommentList()
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onReachBottom () {
    this.loadCommentMore()
  },
  async loadCommentMore () {
    try {
      if (this.loading || this.alloaded) return
      this.loading = true
      let query = {
        materialId: this.data.id,
        currentPage: this.data.currentPage,
        pageSize: this.data.pageSize
      }
      const { ResultSet } = await getMaterialCommentList({ ...query })
      this.alloaded = !ResultSet.userData.data.length
      this.data.isEmpty = !ResultSet.userData.data.length
      this.setData({ isEmpty: this.data.isEmpty })
      if (ResultSet.userData.data.length) {
        this.data.currentPage = this.data.currentPage + 1
        this.data.commentList.push(...ResultSet.userData.data)
        this.setData({
          commentList: this.data.commentList,
          currentPage: this.data.currentPage
        })
      }
      this.loading = false
    } catch (err) {
      this.loading = false
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors })
    }
  },
  async getCommentList () {
    try {
      const { ResultSet } = await getMaterialCommentList({ materialId: this.data.id, currentPage: 1, pageSize: this.data.pageSize })
      this.data.isEmpty = ResultSet.userData.data.length && ResultSet.userData.data.length < this.data.pageSize
      ResultSet.userData.data.forEach(item => {
        item.commentTime = formatTimeTwo(item.commentTime * 1000, 'Y-M-D h:m')
      })
      this.setData({
        currentPage: 2,
        isEmpty: this.data.isEmpty,
        commentList: ResultSet.userData.data
      })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id, scene }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    const userInfo = app.globalData.userInfo ? app.globalData.userInfo : {}
    this.setData({ safeBottom: screenHeight - bottom, userInfo })
    if (scene) {
      let detailId = decodeURIComponent(scene).split('=')[1]
      this.setData({ id: detailId })
    } else {
      this.setData({ id })
    }
    this.getDetail()
  }
})